package com.mw.controller;

import com.mw.domain.AjaxResult;
import com.mw.domain.Dean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeanController {
    @Autowired
    private JdbcClient jdbcClient;

    @GetMapping("/deans")
    public AjaxResult getAll() {
        String sql = """  
            select id, name, password, code, remark  
            from dean  
        """;
        List<Dean> items = jdbcClient.sql(sql)
                .query(Dean.class)
                .list();

        return AjaxResult.success().selectResult(items.size(), items);
    }

    @GetMapping("/deans/{id}")
    public AjaxResult getById(@PathVariable("id") int expectedId) {
        String sql = """  
            select id, name, password, code, remark  
            from dean  
            where id = :id  
        """;

        List<Dean> items = jdbcClient.sql(sql)
                .param("id", expectedId)
                .query(Dean.class)
                .list();

        if (items.isEmpty()) {
            return AjaxResult.error().msg("Dean not found");
        }

        return AjaxResult.success().selectResult(items.size(), items.get(0)); // Assuming only one result for a specific ID
    }

    @PutMapping("/deans")
    public AjaxResult update(@RequestBody Dean dean) {
        String sql = """  
            update dean set   
                name = :name,  
                password = :password,  
                code = :code,  
                remark = :remark   
            where id = :id  
        """;

        int n = jdbcClient.sql(sql)
                .paramSource(dean)
                .update();

        return AjaxResult.success().updateResult(n);
    }

    @DeleteMapping("/deans/{id}")
    public AjaxResult deleteById(@PathVariable("id") int expectedId) {
        String sql = "delete from dean where id = :id";

        int n = jdbcClient.sql(sql)
                .param("id", expectedId)
                .update();

        return AjaxResult.success().deleteResult(n);
    }

    @PostMapping("/deans")
    public AjaxResult insert(@RequestBody Dean dean) {
        String sql = """  
            insert into dean  
                (name, password, code, remark)   
            values  
                (:name, :password, :code, :remark)  
        """;

        int n = jdbcClient.sql(sql)
                .paramSource(dean)
                .update();
        System.out.println("ssssss");

        return AjaxResult.success().insertResult(n);
    }
}